package com.mantou.proxyservice.proxeservice.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mantou.proxyservice.clean.Cleaner;
import com.mantou.proxyservice.proxeservice.entity.Proxy;
import com.mantou.proxyservice.proxeservice.repository.ProxyRepository;
import com.mantou.proxyservice.proxeservice.service.ProxyService;
import com.mantou.proxyservice.utils.ProxyStatus;

@Service
public class ProxyServiceImpl implements ProxyService {

	private int batchSize = 1000;

	@Autowired
	private ProxyRepository proxyRepo;

	@Transactional
	public int create(Proxy proxy) {
		return proxyRepo.insert(proxy);
	}

	@Transactional
	public int createSelective(Proxy proxy) {
		return proxyRepo.insertSelective(proxy);
	}

	@Transactional
	public int deleteByPrimaryKey(Integer id) {
		return proxyRepo.deleteByPrimaryKey(id);
	}

	@Transactional(readOnly = true)
	public Proxy findByPrimaryKey(Integer id) {
		Proxy proxy = proxyRepo.selectByPrimaryKey(id);
		return proxy;
	}

	@Transactional(readOnly = true)
	public int selectCount(Proxy proxy) {
		return proxyRepo.selectCount(proxy);
	}

	@Transactional
	public int updateByPrimaryKey(Proxy proxy) {
		return proxyRepo.updateByPrimaryKey(proxy);
	}

	@Transactional
	public int updateByPrimaryKeySelective(Proxy proxy) {
		return proxyRepo.updateByPrimaryKeySelective(proxy);
	}

	@Override
	public List<Proxy> find4update() {
		// TODO Auto-generated method stub
		int needsize;
		Proxy queryProxy = new Proxy();
		queryProxy.setStatus(ProxyStatus.INIT.getStatus());
		List<Proxy> ret = proxyRepo.selectPage(queryProxy, new PageRequest(0, batchSize));
		needsize = batchSize - ret.size();
		if(needsize <=0)
			return ret;
		queryProxy.setStatus((ProxyStatus.HALFENBLE.getStatus()));
		ret.addAll(proxyRepo.selectPage(queryProxy, new PageRequest(0,(int)(needsize * 0.4),new Sort(Direction.DESC,"lastupdate"))));
		queryProxy.setStatus((ProxyStatus.ENABLE.getStatus()));
		ret.addAll(proxyRepo.selectPage(queryProxy, new PageRequest(0,(int)(needsize * 0.2),new Sort(Direction.DESC,"lastupdate"))));
		needsize = batchSize - ret.size();
		queryProxy.setStatus((ProxyStatus.DISABLE.getStatus()));
		ret.addAll(proxyRepo.selectPage(queryProxy, new PageRequest(0,(int)(needsize),new Sort(Direction.DESC,"lastupdate"))));
		return ret;
	}

	@Override
	public void save(List<Proxy> draftproxys) {
		// TODO Auto-generated method stub
		for(Proxy proxy:draftproxys){
			Proxy queryProxy = new Proxy();
			queryProxy.setIp(proxy.getIp());
			queryProxy.setPort(proxy.getPort());
			if(proxyRepo.selectCount(queryProxy) >=1){
				Cleaner.addconflict(proxy);
			}else{
				proxyRepo.insert(proxy);
			}
		}
	}

}
